package edu.ccut.saturn.studio.wfg.dialog.userdialog.treeoperate;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import edu.ccut.saturn.studio.core.util.eclipse.Messages;
import edu.ccut.saturn.studio.core.util.eclipse.SaturnDialogUtil;
import edu.ccut.saturn.studio.database.model.DBConnection;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.Department;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.ISecondTree;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.OrgnizationPack;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.Role;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.RolePack;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.Third;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.ThirdEnum;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.ThirdFactory;
import edu.ccut.saturn.studio.wfg.dialog.userdialog.User;

public class TreeDataGenerator {
	
	public static Untils untils = null;
	
	private static DBConnection dbConnection = null;
	
	@SuppressWarnings("unchecked")
	public static List<ISecondTree> getTreeData(DBConnection connection){
		untils = Untils.getInstance();
		
		dbConnection = connection;
		List<ISecondTree> secondaryTreeList = new ArrayList<ISecondTree>();
		ISecondTree rolePack = new RolePack(Messages.getString("TreeDataGenerator.auhtor"));   //$NON-NLS-1$
		// 得到"角色"二级树
			
		createRolePack(rolePack,dbConnection);
		secondaryTreeList.add(rolePack);
	 
		ISecondTree departmentPack = new OrgnizationPack(Messages.getString("TreeDataGenerator.Department"));  //$NON-NLS-1$
		 //得到"部门"二级树
	
		secondaryTreeList.add(createDepartmentPack(departmentPack,dbConnection));
		
		return secondaryTreeList;
	}
	
	// 创建"角色"二级树
	@SuppressWarnings("unchecked")
	private static ISecondTree createRolePack(ISecondTree rolePack,DBConnection dbConnection) {
		List<Role> roles = new ArrayList<Role>();

		Connection connection = null;
		Statement stat = null;
		ResultSet rs = null;
		
		try {
			try{
				connection = dbConnection.getConnectionSync();
			} catch (Exception e) {
				SaturnDialogUtil.openError(null, e
						.getMessage());
			}
			
				stat = connection.createStatement();
	            rs = stat.executeQuery("select distinct trole.NAME as rolename, " +
	           		" trole.ID as roleid,tuser.USERNAME as username,tuser.ID as userid from  " +
	           		" saturn_authority_user tuser,saturn_authority_user_role ur," +
	           		" saturn_authority_role trole where tuser.ID = ur.USER_ID and ur.ROLE_ID = trole.ID ");
	           while (rs.next()) {
					String name = rs.getString("rolename");
					String roleID = rs.getString("roleid");
					String user = rs.getString("username");
					String userID = rs.getString("userid");

					Role role = containRoleTree(roles, name);

					if (role != null) {
						if (!(user == null || userID == null)) {
							List<User> UserList = role.getChildren();
							User person = new User();
							person.setName(isNull(user));
							person.setId(isNull(userID));
							person.setType("user");
							UserList.add(person);
						}
					} else {
						Role officialTree = new Role();
						officialTree.setName(isNull(name));
						officialTree.setId(isNull(roleID));
						officialTree.setType("role");
						if (!(user == null || userID == null)) {
							List<User> personTreeList = new ArrayList<User>();
							User person = new User();
							person.setName(user);
							person.setId(userID);
							person.setType("user");
							personTreeList.add(person);
							officialTree.setChildren(personTreeList);
						}
						roles.add(officialTree);
					}
				rolePack.setChildren(roles);
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		} finally {
			try {
					rs.close();
					stat.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}

		return rolePack;
	}
	
	private static Role containRoleTree(List<Role> roles ,String name){
		for(Role tree : roles){
			if(tree.getName().equals(name)){
				return tree;
			}
		}
			return null;
	}
	
	private static String isNull(String value){
		if(value==null){
			return "";
		}
		return value;
	}
	
	// 得到"部门"二级树
	@SuppressWarnings("unchecked")
	private static ISecondTree createDepartmentPack(ISecondTree departmentPack, DBConnection connection){

		List<Third> departments = new ArrayList<Third>();
		Third totel = getTotle(connection);
		if (totel == null) {
			return departmentPack;
		} else {
			List<Third> list = getDepartment(totel.getId(),connection);
			foundeALLDepartment(list,connection);
			totel.setChildren(list);
			departments.add(totel);
			departmentPack.setChildren(departments);
		}
		return departmentPack;
	}
	
	private static void foundeALLDepartment(List<Third> list, DBConnection connection) {
		for (Third t : list) {
			if (t instanceof Department) {
				//获取部门下的岗位
//				List<Third> positionList = getPosition(t.getId());
				//获取部门下用户
				List<Third> userList = getUsers(t.getId(), null, connection);
				List<Third> list2 = getDepartment(t.getId(), connection);
				if (userList.size() != 0) {
					for (Third user : userList) {
						list2.add(user);
					}
				}
//				if (positionList.size() != 0) {
//					for (Third position : positionList) {
//						list2.add(position);
//					}
//				}
				t.setChildren(list2);
				if (list2.size() != 0 && list2 != null) {
					foundeALLDepartment(list2 ,connection);
				}
			}
		}
	}
	
//	private static List<Third> getPosition(String id){
//		Untils until = Untils.getInstance();
//		String ss [] = new String[]{id};
//		ResultSet re = until.getSelectResult(SqlLoader.getSqlCode(SelectInformation.INQUIREPOSITIONBYID), ss);
//		List<Third> list = new ArrayList<Third>();
//		if(re!=null){
//			try {
//				while(re.next()){
//					Third th = ThirdFactory.getThird(ThirdEnum.POSITION);
//					th.setName(re.getString("name"));
//					th.setId(re.getString("id"));
//					th.setChildren(getUsers(th.getId(),id));
//					list.add(th);
//				}
//			} catch (SQLException e) {
//				e.printStackTrace();
//			}finally{
//				if(re!=null){
//					try {
//						re.close();
//						until.closeStatement();
//					} catch (SQLException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//		}
//		return list;
//	}
	
	private static List<Third> getUsers(String id,String position,DBConnection connection){
		String ss [] = new String[]{id};
		ResultSet re = untils.getSelectResult(SqlLoader.getSqlCode(SelectInformation.INQUIREUSERBYDEPARTMENTID), ss ,connection);
		List<Third> list = new ArrayList<Third>();
		if(re!=null){
			try {
				while(re.next()){
					Third user = ThirdFactory.getThird(ThirdEnum.USER);
					user.setName(re.getString("USERNAME"));
					user.setId(re.getString("id"));
					list.add(user);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				if(re!=null){
					try {
						re.close();
						untils.closeStatement();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return list;
	}
	
	
	private static List<Third> getDepartment(String id, DBConnection connection){
		String ss [] = new String[]{id};
		ResultSet re = untils.getSelectResult(SqlLoader.getSqlCode(SelectInformation.INQUIRESUBDEPTBYID), ss ,connection );
		List<Third> list = new ArrayList<Third>();
		if(re!=null){
			try {
				while(re.next()){
					Third th = ThirdFactory.getThird(ThirdEnum.DEPARTMENT);
					th.setName(re.getString("name"));
					th.setId(re.getString("id"));
					list.add(th);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				if(re!=null){
					try {
						re.close();
						untils.closeStatement();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return list;
	}
	
	private static Third getTotle(DBConnection connection){
		ResultSet re = untils.getSelectResult(SqlLoader.getSqlCode(SelectInformation.INQUIREHEADQUARTERID), null,connection);
		if(re!=null){
			try {
				while(re.next()){
					Third th = ThirdFactory.getThird(ThirdEnum.DEPARTMENT);
					th.setName(re.getString("name"));
					th.setId(re.getString("id"));
					return th;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				if(re!=null){
					try {
						re.close();
						untils.closeStatement();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
			}
		}
			return null;
	}
}
